#!/bin/bash
backup_path="/sharedfolders/git/gitea"

backup_path_docker="/backup"

backup_filename=${backup_path_docker}/$(date "+gitea-backup-%Y%m%d_%H%M%S")

cd $(dirname $0)

# ls -1 ${backup_path}
# 恢复备份
PS3="请选择恢复的备份: "
menu=$(ls -1 ${backup_path} |  sed -n 's/gitea-backup-\(20[0-9]\{6\}_[0-9]\{6\}\)\.tgz/\1/g p' )

select dump_filename in ${menu} "退出"
do
  if [ -n "${dump_filename}" ]; then 
    case "${dump_filename}" in
      "退出")
        exit 1 
        ;;
      *)
        break 
        ;;
    esac  
  fi
done

dump_filename="gitea-backup-${dump_filename}.tgz"

read -n1 -p "恢复备份 : ${dump_filename} (N/y)? : " answer 
case $answer in 
  Y|y) 
    echo
    cid=$(docker-compose ps -q gitea)
    if [ ${#cid} -gt 0 ]; then
      docker-compose down
    fi

    docker-compose run --rm  gitea sh -c "/app/gitea/gitea -v >/data/gitea/version.txt &&cd /data &&sqlite3 /data/gitea/gitea.db .dump >/data/gitea/gitea.sql&&echo "备份当前文件到  ${backup_filename}.tgz  &&tar -zcpf ${backup_filename}.tgz ssh gitea git && chown git:users /backup -R && chmod -R a+r ${backup_path_docker}/* && rm -rf /data/* && echo "恢复备份 ${dump_filename} ..." && tar -zxf ${backup_path_docker}/${dump_filename} "

    # mkdir -p ./data
    # docker-compose up -d
    # cd /data
    # docker-compose -rm run gitea sh -c  "mv /data/gitea /data/$(date '+gitea_%Y%m%d_%H%M%S.bak')"
    # echo "解压文件..."
    # sudo tar -zxf ${backup_path}/${dump_filename}
    echo "恢复完毕."
    echo "启动 Gitea ..."
    # cd $(dirname ${BASH_SOURCE:-$0})
    docker-compose up -d
    ;;
  *)
    echo
    exit 1
    ;;
esac
